import requests
import json


# 信息类
class Info:
    # 基本参数字典
    params = {
        'access_token': '',
        'page': '',
        'per_page': '100',
        'role': 'all'
    }
    # api方法格式化字典
    urls_format = {
        'orgs': {
            '': 'org_1',
            'members': 'org_2',
            'repos': 'org_2'
        },
        'repos': {
            'collaborators': 'owner_repo_2',
            'commits': 'owner_repo_2',
            'issues': 'owner_repo_2'
        },
        'users': {
            '': 'username_1',
            'followers': 'username_2'
        }
    }

    # 初始化，data为参数字典，传入令牌、组织名称等
    def __init__(self, data):
        self.api = 'https://gitee.com/api/v5'
        self.params['access_token'] = str(data.get('access_token'))
        self.org = str(data.get('org'))
        self.username = str(data.get('username'))
        self.owner = str(data.get('owner'))
        self.repo = str(data.get('repo'))

    # 获取组织的成员/仓库信息
    def __get_info(self, param1, param2):
        item_info = []
        # 页数
        page = 1
        # 旗子，已经有页面内容小于最大容量100，那么判定为搜索完成（因为有的函数不需要page参数）
        flag = False
        # api方法字典
        urls = {
            'org_1': '/'.join([self.api, param1, self.org]),
            'org_2': '/'.join([self.api, param1, self.org, param2]),
            'owner_repo_2': '/'.join([self.api, param1, self.owner, self.repo, param2]),
            'username_1': '/'.join([self.api, param1, self.username]),
            'username_2': '/'.join([self.api, param1, self.username, param2]),
        }
        while 1:
            self.params['page'] = str(page)
            r = requests.get(urls[self.urls_format[param1][param2]], params=self.params)
            r = json.loads(r.text)
            # 某些单搜索返回值是字典不是列表
            if type(r) == dict:
                r = [r]
            if not flag:
                item_info += r
                if len(r) < 100:
                    flag = True
            else:
                break
            page += 1
        return item_info

    # 获取组织信息
    def get_orgs_info(self):
        return self.__get_info('orgs', '')

    # 获取组织的成员信息
    def get_orgs_members_info(self):
        return self.__get_info('orgs', 'members')

    # 获取组织的仓库信息
    def get_orgs_repos_info(self):
        return self.__get_info('orgs', 'repos')

    # 获取所有者的仓库的成员信息
    def get_repos_collaborators_info(self):
        return self.__get_info('repos', 'collaborators')

    # 获取所有者的仓库的提交信息
    def get_repos_commits_info(self):
        return self.__get_info('repos', 'commits')

    # 获取所有者的仓库的问题信息
    def get_repos_issues_info(self):
        return self.__get_info('repos', 'issues')

    # 获取用户信息
    def get_users_info(self):
        return self.__get_info('users', '')

    # 获取用户的关注者信息
    def get_users_followers_info(self):
        return self.__get_info('users', 'followers')
